import { createAlova } from 'alova'
import GlobalFetch from 'alova/GlobalFetch'
import VueHook from 'alova/vue'
import { message } from 'ant-design-vue'
import { remove } from 'es-cookie'
import { redirect } from '@/tools/login-redirect'

interface Json {
  Code: number
  Data: any
  Message: string
}

export const alovaInstance = createAlova({
  statesHook: VueHook,
  baseURL: '/api/v1',
  requestAdapter: GlobalFetch(),
  responded: {
    onSuccess: async (response) => {
      if (response.status !== 200) {
        message.error(`服务请求失败${response.status}`)
        return Promise.reject(response)
      }
      const json: Json = await response.json()
      const { Code, Message } = json

      if (Code === 401) {
        remove('token')
        message.error(Message || '登录态失效')
        setTimeout(() => {
          redirect()
        }, 500)
        return Promise.reject(response)
      }
      if (json.Code !== 200) {
        message.error(Message || '请求失败')
        return Promise.reject(response)
      }
      return Promise.resolve(json)
    },
    onError: error => Promise.reject(error),
  },
})
